const Service = require('egg').Service;

class BlogService extends Service {
    async getList() {
        // controller只负责收发数据
        // service 负责复杂业务逻辑
        const {ctx,app} = this;
        // 分页 模糊查询 排序 id
        const {pageIndex,pageSize, keyword, sortBy,sortType, id} = ctx.query;
        // const data = await app.mysql.select('blogs', {
        //     where: {id},
        //     orders: [[sortBy,sortType]], // 排序方式
        //     limit: pageSize, // 返回数据量
        //     offset: (pageIndex-1)*pageSize, // 数据偏移量
        // });// 不支持模糊查询和or 等  难以完成复杂业务操作
        let sql = `select * from blogs where 1=1 `
        let totalSql = `select count(id) as total from blogs where 1=1 `
        if(keyword){
            sql+=`and title like "%${keyword}%" `
            totalSql+=`and title like "%${keyword}%" `
        }
        if(id) {
            sql+=`and id =${id} `
            totalSql+=`and id =${id} `
        }
        if(sortBy&&sortType){
            sql+= `order by ${sortBy} ${sortType} `
        }
        if(pageIndex&&pageSize) {
            sql+= `limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        const data = await app.mysql.query(sql);
        const [{total}] = await app.mysql.query(totalSql);
        return {
            data,
            total
        }
    }
    async addList() {
        const {ctx,app} = this;
        const data = await app.mysql.insert('blogs', {...ctx.request.body,create_time: Date.now()})
        return data
    }
    async editList() {
        const {ctx,app} = this;
        const data = await app.mysql.update('blogs', {...ctx.request.body});// 参数里必须有id
        return data
    }
    async delList() {
        const {ctx,app} = this;
        const data = await app.mysql.delete('blogs', {id:ctx.params.id});// 根据id删除
        return data
    }
}

module.exports = BlogService;
